const { createStoreBindings } = require('mobx-miniprogram-bindings');
const { materialListStore } = require('../../../config/store_config.js');
// 导入路径辅助模块，避免重复引用
const pathImport = require('../helpers/path_import.js');
const { pageHelper, cloudHelper } = pathImport;;

Page({
    data: {
        isLoad: false,
        cateId: '', 
        searchKey: '',
        isAdmin: false
    },

    onLoad: function (options) {
        if (!options.cateId) {
            pageHelper.showNoneToast('参数错误');
            setTimeout(() => {
                wx.navigateBack();
            }, 1500);
            return;
        }

        this.setData({
            cateId: options.cateId
        });

        // 创建MobX绑定
        this.storeBindings = createStoreBindings(this, {
            store: materialListStore,
            fields: ['materials', 'hasMore', 'loading'],
            actions: ['fetchMaterials', 'searchMaterials', 'refreshList', 'loadMore']
        });

        // 检查用户权限
        this.checkUserRole();

        // The request will be made with the set cateId
        materialListStore.setCateId(options.cateId);
        
        // 加载资料数据
        this.loadData();
    },

    checkUserRole: async function() {
        try {
            const res = await cloudHelper.callCloudData('user/role', {});
            
            if (res && res.data && res.data.isAdmin) {
                this.setData({
                    isAdmin: true
                });
            }
        } catch (err) {
            console.error('获取用户角色失败', err);
        }
    },

    loadData: function () {
        materialListStore.refreshList()
            .then(() => {
                this.setData({
                    isLoad: true
                });
            })
            .catch(err => {
                console.error('获取资料失败', err);
                pageHelper.showNoneToast('获取资料失败，请稍后重试');
            });
    },

    onSearchInput: function(e) {
        this.setData({
            searchKey: e.detail.value
        });
        
        // 防抖处理
        if (this.searchTimer) {
            clearTimeout(this.searchTimer);
        }
        
        this.searchTimer = setTimeout(() => {
            materialListStore.searchMaterials(this.data.searchKey);
        }, 300);
    },

    onShowFilter: function() {
        // 显示筛选弹窗
        wx.showActionSheet({
            itemList: ['全部', '草稿', '已发布', '生产版本', '已废弃'],
            success: (res) => {
                const statusMap = [null, 1, 2, 3, 4]; // 对应状态值
                materialListStore.setStatusFilter(statusMap[res.tapIndex]);
                materialListStore.refreshList();
            }
        });
    },

    onMaterialTap: function(e) {
        const id = e.currentTarget.dataset.id;
        // 跳转到资料详情页
        wx.navigateTo({
            url: `/projects/oa/pages/material/detail/material_detail?id=${id}`
        });
    },

    onAddMaterial: function() {
        // 跳转到添加资料页
        wx.navigateTo({
            url: `/projects/oa/pages/material/edit/material_edit?cateId=${this.data.cateId}`
        });
    },

    onPullDownRefresh: function () {
        // 下拉刷新
        materialListStore.refreshList()
            .then(() => {
                wx.stopPullDownRefresh();
            });
    },

    onReachBottom: function () {
        // 上拉加载更多
        if (this.data.hasMore && !this.data.loading) {
            materialListStore.loadMore();
        }
    },

    onUnload: function () {
        // 清理搜索定时器
        if (this.searchTimer) {
            clearTimeout(this.searchTimer);
        }
        
        // 释放MobX绑定
        this.storeBindings.destroyStoreBindings();
    }
}) 